﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Objects;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;

namespace DataProject
{
    public class MemorySet<TEntity> : IObjectSet<TEntity> where TEntity : class
    {
        #region constructor

        public MemorySet(List<TEntity> innerList)
        {
            if (innerList == null)
            {
                throw new ArgumentNullException("innerList", string.Format(CultureInfo.InvariantCulture, Resources.Messages.ArgumentCannotBeNull, "innerList"));
            }

            this.InnerList = innerList;
            this.IncludePaths = new List<string>();
        }

        #endregion

        #region public properties

        public Type ElementType
        {
            get
            {
                return typeof(TEntity);
            }
        }

        public Expression Expression
        {
            get
            {
                return this.InnerList.AsQueryable().Expression;
            }
        }

        public IQueryProvider Provider
        {
            get
            {
                return this.InnerList.AsQueryable().Provider;
            }
        }

        #endregion

        #region private fields

        private List<TEntity> InnerList { get; set; }

        private List<string> IncludePaths { get; set; }

        #endregion

        #region public methods

        public MemorySet<TEntity> Include(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException("path", string.Format(CultureInfo.InvariantCulture, Resources.Messages.ArgumentCannotBeNull, "path"));
            }

            this.IncludePaths.Add(path);

            return this;
        }

        public void AddObject(TEntity entity)
        {
            if (entity != null)
            {
                this.InnerList.Add(entity);
            }
        }

        public void Attach(TEntity entity)
        {
            if (entity != null && !this.InnerList.Contains(entity))
            {
                this.InnerList.Add(entity);
            }
        }

        public void Detach(TEntity entity)
        {
            if (entity != null)
            {
                this.InnerList.Remove(entity);
            }
        }

        public void DeleteObject(TEntity entity)
        {
            if (entity != null)
            {
                this.InnerList.Remove(entity);
            }
        }

        public IEnumerator<TEntity> GetEnumerator()
        {
            foreach (TEntity item in this.InnerList)
            {
                yield return item;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        #endregion
    }
}
